<?php

namespace App\Services;

use App\Models\EmailVerificationCode;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;

class EmailVerificationService
{
    public function sendVerificationCode($email)
    {
        // 生成6位随机验证码
        $code = Str::random(6);
        
        // 保存验证码到数据库
        EmailVerificationCode::create([
            'email' => $email,
            'code' => $code,
            'expires_at' => now()->addMinutes(15)
        ]);

        // 发送验证码邮件
        Mail::send('emails.verification-code', ['code' => $code], function($message) use ($email) {
            $message->to($email)->subject('邮箱验证码');
        });

        return true;
    }

    public function verifyCode($email, $code)
    {
        $verification = EmailVerificationCode::where('email', $email)
            ->where('code', $code)
            ->where('expires_at', '>', now())
            ->first();

        if (!$verification) {
            return false;
        }

        // 删除已使用的验证码
        $verification->delete();

        return true;
    }
} 